const pool = require("../database.js");
const jwt = require("jsonwebtoken");
const fs = require("fs");
const errorTypes = require("../app/error-types");
const path = require("path");
exports.getList = async function getList(ctx, data) {
  try {
    let offset, start, limit, statement2, result2;
    let limitState = "";
    let query = [];
    let otherData = [];
    if (!data.notList) {
      start = ctx.query?.start || String(0);
      limit = ctx.query?.limit || String(10);
      offset = start !== "0" ? String((start - 1) * limit) : "0";
      limitState = "LIMIT ?,?;";
      query.push(...[offset, limit]);
      statement2 = `${data.statement || "SELECT COUNT(*) FROM " + data?.table} ${data?.otherState || ""};`;
      [result2] = await pool.execute(statement2, otherData.length > 0 ? [...otherData] : []);
    }
    if (data?.data && data?.data?.length > 0) {
      otherData = data?.data && data?.data?.length > 0 ? data?.data : [];
      query.push(...otherData);
    }
    const statement = `${data.statement || "SELECT * FROM " + data?.table}  ${data?.otherState || ""} ${limitState}`;
    //  console.log(statement);
    console.log(statement, query);
    const [result] = await pool.execute(statement, query);
    console.log(result);
    if (data.notBody) return { data: result[0], flag: true };
    if (data.notList) return (ctx.body = { data: result[0], flag: true });
    ctx.body = { data: { dataList: result, total: result2.length > 0 ? result2[0]["COUNT(*)"] : 0 }, flag: true };
  } catch (erro) {
    console.log(erro);
    console.log(erro);
    const error = new Error("系统错误");
    return ctx.app.emit("error", error, ctx);
  }
};
exports.postData = async function postData({ table, data, ctx, multiInsert, notNext }) {
  try {
    let value = [];
    let key = [];
    let stateQuery = [];
    let index = 0;
    let position = 0;
    for (let item in data) {
      key.push(item);
      value.push("?");
      if (multiInsert == item) position = index;
      index += 1;
      stateQuery.push(data[item]);
    }
    value = "(" + value.join(",") + ")";
    let mutistateQuery = [];
    if (multiInsert) {
      let str = [];
      data[multiInsert].map((item, index) => {
        str.push(value);
        stateQuery[position] = item;
        mutistateQuery.push(...stateQuery);
      });
      value = str.join(",");
      stateQuery = mutistateQuery;
    }
    key = key.join(",");
    const statement = `INSERT INTO ${table} (${key}) VALUES ${value}`;
    //  console.log(statement);
    let result = await pool.execute(statement, stateQuery);
    if (notNext) return result[0];
    ctx.body = { data: "提交成功", flag: true };
  } catch (erro) {
    console.log(erro);
    const error = new Error("系统错误");
    return ctx.app.emit("error", error, ctx);
  }
};
exports.putData = async function putData(table, data, ctx) {
  try {
    let stateQuery = [];
    let value = ``;
    for (let item in data) {
      value += "`" + item + "`=?,";
      stateQuery.push(data[item]);
    }
    value = value.slice(0, value.length - 1);
    const statement = `UPDATE ${table} SET ${value} WHERE id =?`;
    await pool.execute(statement, [...stateQuery, data.id]);
    ctx.body = { data: "修改成功", flag: true };
  } catch (erro) {
    const error = new Error("系统错误");
    return ctx.app.emit("error", error, ctx);
  }
};
exports.deleteData = async function deleteData(table, id, ctx) {
  try {
    const statement = `DELETE FROM ${table} WHERE id = ${id}`;
    await pool.execute(statement, []);
    ctx.body = { data: "删除成功", flag: true };
  } catch (erro) {
    console.log(erro);
    const error = new Error("系统错误");
    return ctx.app.emit("error", error, ctx);
  }
};
exports.anthVertify = async function anthVertify(ctx, next) {
  try {
    const PUBLIC_KEY = fs.readFileSync(path.resolve(__dirname, "./public.key"));
    let authorization = ctx.req.headers.authorization;
    const result = jwt.verify(authorization, PUBLIC_KEY, {
      algorithms: ["RS256"],
    });
    ctx.user = result;
    // next()报错到不了下一个中间件就报错 这里的没有token 所以不能在这个next
    // await next();
  } catch (err) {
    console.log(err);
    const error = new Error(errorTypes.UNAUTHORIZATION);
    return ctx.app.emit("error", error, ctx);
  }
  await next();
};
exports.getListAll = async function getListAll(ctx, { table, queryData, data, otherState }) {
  try {
    data = data && data.length > 0 ? data : [];
    const statement = `SELECT ${queryData ? queryData : "*"} FROM ${table} ${otherState || ""};`;
    const [result] = await pool.execute(statement, data.length > 0 ? [...data] : []);
    return { data: result, flag: true };
  } catch (erro) {
    console.log(erro);
    const error = new Error("系统错误");
    return ctx.app.emit("error", error, ctx);
  }
};
